<?php

/**
 * Description of TextMessage
 *
 * @author Ian Clarence <ian.clarence@gmail.com>
 */
class TextMessage extends ActiveRecord {

    /**
     * The table name.
     */
    const TABLE = 'text_message';

    /**
     * The constructor.
     *
     * @param array $fields
     */
    public function __construct(array $fields = array()) {
        parent::__construct($fields);
    }

    /**
     * Getting the text message in the current language.
     *
     * @param string $textKey
     * @return string
     */
    public static function getTextMessage($textKey) {
        $languageCode = Utils::getLanguage();

        /**
         * Not a multilingual site: language irrelevant.
         */
        if ($languageCode === FALSE) {
            $apcKey = static::TABLE . $textKey;
            $params = array('table' => static::TABLE, 'text_key' => $textKey);
            $callback = function($params) {
                    $query = new Query('
                        SELECT `message`
                        FROM :table
                        WHERE `text_key` = :text_key;
                    ');
                    $query->bindFieldName('table', $params['table']);
                    $query->bindVariable('text_key', $params['text_key']);
                    return System::getDB()->queryArray($query, TRUE);
            };        
            $fields = Utils::apcCache($apcKey, $callback, STORED_AS_CACHE == YES, $params);
            
            
        }

        /**
         * Multilingual site.
         */
        else {
            $apcKey = static::TABLE . $textKey . '_' . $languageCode;
            $params = array('table' => static::TABLE, 'text_key' => $textKey, 'language_code' => $languageCode);
            $callback = function($params) {
                $query = new Query('
                    SELECT `message`
                    FROM :table AS `tm`
                    INNER JOIN `language` AS `l`
                    ON `l`.`id` = `tm`.`language`
                    WHERE `l`.`code` = :language_code
                    AND `tm`.`text_key` = :text_key;
                ');
                $query->bindFieldName('table', $params['table']);
                $query->bindVariable('language_code', $params['language_code']);
                $query->bindVariable('text_key', $params['text_key']);
                return System::getDB()->queryArray($query, TRUE);
            };        
            $fields = Utils::apcCache($apcKey, $callback, STORED_AS_CACHE == YES, $params);
            
        }

        return $fields['message'];

    }

}